<?php
require_once 'config.php';


function authenticate_user() {
    if (!isset($_SESSION['user_id'])) {
        header('Location: /login.php?redirect='.urlencode($_SERVER['REQUEST_URI']));
        exit();
    }
}

function check_role($required_role) {
    authenticate_user();

    if ($_SESSION['user_role'] !== $required_role) {
        http_response_code(403);
        include('errors/403.php');
        exit();
    }
}

function login_user($username, $password) {
    global $pdo;

    $stmt = $pdo->prepare("SELECT id, password_hash, role FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_role'] = $user['role'];
        session_regenerate_id(true);

        return true;
    }
    return false;
}

function logout_user() {
    $_SESSION = [];
    session_destroy();
    setcookie(session_name(), '', time()-3600, '/');
}

//// 在auth.php中添加
//function require_admin() {
//    if ($_SESSION['user_role'] !== 'admin') {
//        header('HTTP/1.1 403 Forbidden');
//        include('403.php');
//        exit();
//    }
//}
// 新增权限校验增强
function require_admin() {
    if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
        log_audit('未授权访问尝试', $_SERVER['REQUEST_URI']);
        header('Location: /errors/403.php');
        exit();
    }
}

// 审计日志功能
function log_audit($action, $details) {
    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO audit_logs (user_id, action, details) VALUES (?, ?, ?)");
    $stmt->execute([$_SESSION['user_id'] ?? 0, $action, $details]);
}

// 增强后的check_role函数
/**
 @param $required_role
 @return void
 */
function check_role($required_role) {
    if (!isset($_SESSION['user_id'])) {
        header('Location: /login.php?redirect='.urlencode($_SERVER['REQUEST_URI']));
        exit();
    }

    if ($_SESSION['user_role'] !== $required_role) {
        log_audit('角色权限不足', "需要角色: $required_role");
        header('Location: /errors/403.php');
        exit();
    }
    $user_role = $_SESSION['user_role'] ?? '';
    if ($user_role !== $required_role) {
        log_audit('权限越权访问', "访问路径: {$_SERVER['REQUEST_URI']}");
        header('HTTP/1.1 403 Forbidden');
        exit();
    }
}
